package liwen.zhao.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import liwen.zhao.common.jd.pojo.Article;
import liwen.zhao.common.jd.vo.SysResult;
import liwen.zhao.mappers.ArticleMapper;
import liwen.zhao.utils.ESUtil;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ElasticsearchServiceImpl implements ElasticsearchService {
    @Autowired
    private TransportClient transportClient;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    private ESUtil esUtil;
    private ObjectMapper mapper=new ObjectMapper();
    @Override
    public SysResult createIndexByNameAndType(String indexName,String type) {
        try{
            TransportClient client = esUtil.indexIsExists(indexName);
            //创建索引成功
            //将document数据写入到索引中 type
            //读取数据库数 0,100
            List<Article> articles = articleMapper.selectArticleByPage(0, 100);
            for(Article a:articles){
                //每次拿到一个商品对象
                //String aJson = mapper.writeValueAsString(p);
                Map<String ,String> articleMap=new HashMap<String ,String>();
                articleMap.put("id",a.getId()+"");
                articleMap.put("title",a.getTitle());
                articleMap.put("content",a.getContent());
                articleMap.put("img",a.getImg());
                articleMap.put("price",a.getPrice()+"");
                client.prepareIndex(indexName,type,a.getId()+"")
                        .setSource(articleMap).get();
            }
            return SysResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return SysResult.build(500,"索引创建失败！",null);
        }
    }
    
    @Override
    public List<Article> search(String text, Integer page, Integer rows) throws IOException {
        //封装一个query对象
        MatchQueryBuilder query = QueryBuilders.matchQuery("title", text);
        if(text.equals("")){
            query=null;
        }
        //搜索分页逻辑
        int from=(page-1)*rows;
        int size=rows;
        SearchRequestBuilder request = transportClient.prepareSearch("jd")
                .setQuery(query).setFrom(from).setSize(size);
        //命令发送
        SearchResponse searchResponse = request.get();
        //从response中解析数据,封装成返回结果
        List<Article> aList=new ArrayList<Article>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for(SearchHit hit:hits){
            //sourceAsString {"":"","":"","":""}
            String aJson = hit.getSourceAsString();
            Article article = mapper.readValue(aJson, Article.class);
            aList.add(article);
        }
        return aList;
    }
}
